<template>
	<view class="container">
		<!-- 顶部状态栏 -->
		<view class="tab-header sticky">
			<view class="tab-item" 
					v-for="tab in tabs" 
					:key="tab.id"
					:class="{active: tabIndex === tab.id}" 
					@click="switchTab(tab.id)">
				<text>{{tab.text}}</text>
				<view class="tab-line"></view>
			</view>
		</view>

		<!-- 订单列表 -->
		<view class="order-list">
			<view class="order-item" v-for="(item, index) in orderList" :key="index">
				<view class="order-header" @click="toOrderDetail(item)">
					<text class="order-no">{{ item.orderNumber }}</text>
					<text class="order-time">下单时间：{{ item.createTime | formatTime }}</text>
				</view>

				<view class="order-content" @click="toOrderDetail(item)">
					<view class="flex-column" style="align-self: center;">
						<circle-progress
							v-if="item.status != -1"
							:progress="item.soc || 0"
							:status="statusText[item.status]"
							:statusProgressColor="statusColor[item.status]['statusProgressColor']"
							:progressColor="statusColor[item.status]['progressColor']"
						/>
						<circle-progress v-else :progress="item.soc || 0" status="结束异常" statusProgressColor="#FC0A01" progressColor="rgba(252, 10, 1, 0.2)" />
					</view>
					<view class="charging-info">
						<view class="info-item">
							<text class="title">{{item.stationName}}</text>
						</view>
						<view class="info-item">
							<text class="label">已充电量:</text>
							<text class="value">{{ item.chargedEnergy }}度</text>
						</view>
						<view class="info-item">
							<text class="label">充电时长:</text>
							<text class="value">{{ item.chargingDuration | formatMinutes }}</text>
						</view>
						<view class="info-item">
							<text class="label">终端名称:</text>
							<text class="value">{{ item.terminalName }}</text>
						</view>
						<view class="info-item">
							<text class="label">终端编号:</text>
							<text class="value">{{ item.terminalId }}</text>
						</view>
						<view class="info-item">
							<text class="label">充电枪号:</text>
							<text class="value">{{ item.gunCode }}</text>
						</view>
					</view>

					<view class="order-amount">
						<view class="order-status" 
							v-if="item.status != -1"
							:style="{
								background: statusColor[item.status]['statusBackgroundColor'], 
								color: statusColor[item.status]['statusTextColor'], 
								border: `1px solid ${statusColor[item.status]['statusTextColor']}`
							}"
						>{{ statusText[item.status] }}</view>
						
						<view class="order-status abnormal" v-if="item.status == -1">异常</view>
						
						<block>
							<text class="amount">{{ item.chargedAmount }}元</text>
							<text class="amount-label">已充金额</text>
						</block>
					</view>
				</view>
				
				<!-- 订单操作按钮 -->
				<view class="buttons flex justify-end" v-if="item.status === 2 || item.status === 0">
					<view class="button" v-if="item.status === 2" @click="handlePay(item)">立即支付</view>
					<view class="button" v-if="item.status === 0" @click="handleStopCharging(item)">结束充电</view>
				</view>
			</view>
		</view>
		
		<!-- 数据为空 -->
		<view class="empty" v-if="orderList.length == 0">
			<u-empty mode="data"></u-empty>
		</view>
		
		<!-- 加载更多 -->
		<u-loadmore v-if="orderList && orderList.length > 0" :status="loadMoreStatus" />

		<!-- 底部导航栏 -->
		<com-tabbar :currentTab="currentTab"></com-tabbar>

		<!-- 优惠券选择器组件 -->
		<coupon-selector 
			ref="couponSelector"
			:orderAmount="currentOrderAmount"
			:coupons="availableCoupons"
			@select="onCouponSelect"
		/>

		<payment 
			v-if="currentOrder && currentOrder.id"
			:show="showPayment"
			:amount="currentOrderAmount"
			:orderId="currentOrder.id"
			:payOrderId="currentOrder.orderNumber"
			@payment-success="onPaymentSuccess"
			@payment-error="onPaymentFail"
			@close="showPayment = false"
		/>
	</view>
</template>

<script>
	import { mapState, mapActions } from 'vuex'
	import CircleProgress from '@/components/circle-progress/circle-progress.vue'
	import { formatWeChatTime, formatMinutes, formatTimestamp, formatNewTimestamp } from '@/utils/index.js'
	import CouponSelector from '@/components/coupon-selector'
	import Payment from '@/components/payment/payment.vue'
	export default {
		components: {
			CircleProgress,
			CouponSelector,
			Payment
		},
		data() {
			return {
				currentTab: 'order',
				tabIndex: -1,
				orderList: [],
				statusText: ['进行中', '结算中', '待支付', '已支付', '已开票', '开票中'],
				statusColor: [
					{ statusProgressColor: '#FF4600', progressColor: '#FFE4DB',  statusTextColor: '#1C6EFB', statusBackgroundColor: '#E7F2FF' },
					{ statusProgressColor: '#FF9900', progressColor: 'rgba(255, 153, 0, 0.3)',  statusTextColor: '#FF9900', statusBackgroundColor: '#FFF4E6' },
					{ statusProgressColor: '#FF4600', progressColor: '#FFE4DB',  statusTextColor: '#FF4600', statusBackgroundColor: '#FFE4DB' },
					{ statusProgressColor: '#42E0A2', progressColor: 'rgba(66, 224, 162, 0.3)',  statusTextColor: '#42E0A2', statusBackgroundColor: '#E6FFF5' },
					{ statusProgressColor: '#42e0a2', progressColor: 'rgba(66, 224, 162, 0.3)',  statusTextColor: '#42E0A2', statusBackgroundColor: '#E6FFF5' },
					{ statusProgressColor: '#FF9900', progressColor: 'rgba(255, 153, 0, 0.3)',  statusTextColor: '#FF9900', statusBackgroundColor: '#FFF4E6' },
				],
				formData: {
					pageNo: 1,
					pageSize: 15,
					status: '',
				},
				isLoading: false,
				isFinished: false,
				tabs: [
					// 0-进行中1-结算中2-待支付3-已支付4-已开票5-开票中
					{ id: -1, text: '全部' },
					// { id: 2, text: '待支付' },
					{ id: 3, text: '已支付' },
					{ id: 0, text: '进行中' },
					// { id: 1, text: '结算中' },
					{ id: 5, text: '开票中' },
					{ id: 4, text: '已开票' },
				],
				showPayment: false,
				currentOrderAmount: 0,
				selectedCoupon: null,
				currentOrder: null,
				availableCoupons: []
			}
		},
		computed: {
			//引入store全局变量
			...mapState(['loginState', 'userInfo']),
			
			loadMoreStatus() {
				if (this.isLoading) return 'loading'
				if (this.isFinished) return 'nomore'
				return 'loadmore'
			}
		},
		onLoad() {
			this.getlist(true);
			uni.$on('loginSuccessEvent', () => {
				this.isFinished = false;
				this.isLoading = false;
				this.getlist(true);
			});
		},
		onShow() {
			if (this.formData.pageNo == 1) {
				this.isLoading = false;
				this.isFinished = false;
				this.getlist(true);
			}
			if (!this.loginState) {
				this.resetOrderList();
			}
		},
		onReachBottom() {
			this.formData.pageNo += 1;
			this.getlist()
		},
		methods: {
			resetOrderList() {
				this.formData.pageNo = 1;
				this.isLoading = false;
				this.isFinished = false;
				this.orderList = [];
				this.getlist()
			},
			// 订单列表
			getlist(refresh = false) {
				if (this.isFinished || this.isLoading) return
				this.isLoading = true
				
				// Reset pagination if refreshing
				if (refresh) {
					this.formData.pageNo = 1
					this.isFinished = false
				}
				
				const formData = JSON.parse(JSON.stringify(this.formData))
				if (formData.status == '' && formData.status != 0) {
					delete formData.status
				}
				this.$http_api.orderList(formData).then((res) => {
					if(res){
						const { records, total } = res;
						this.orderList = this.formData.pageNo === 1 ? records : [...this.orderList, ...records]
						this.isFinished = records.length < 15
					}
				}).finally(() => {
					this.isLoading = false
				})
			},
			//订单详情
			toOrderDetail(orderInfo) {
				uni.navigateTo({
					url: '/pages/order/order-detail?id=' + orderInfo.id
				})
			},
			//切换导航
			switchTab(index) {
				this.tabIndex = index;
				this.isFinished = false;
				this.isLoading = false;
				this.orderList = [];
				if (index === -1) {
					this.formData.status = '';
				} else {
					this.formData.status = index;
				}
				this.formData.pageNo = 1;
				this.getlist();
			},
			// 发起支付
			handlePay(order) {
				this.currentOrder = order
				this.currentOrderAmount = order.chargedAmount
				this.showPayment = true
			},
			// 停止充电
			handleStopCharging(order) {
				// 先弹出确认框
				uni.showModal({
					title: '确认结束充电',
					content: '是否确认结束当前充电?',
					success: (res) => {
						if (res.confirm) {
							// 用户点击确定后继续原有逻辑
							this.currentOrder = order
							this.currentOrderAmount = order.chargedAmount * 100
							this.confirmStopCharging()
							
							// 检查是否有可用优惠券
							/**
							this.$http_api.couponList({ status: 1, pageNo: 1, pageSize: 100 }).then(res => {
								this.availableCoupons = (res.list || []).filter(coupon => {
									return parseFloat(this.currentOrderAmount) >= parseFloat(coupon.usePrice)
								})
								if (this.availableCoupons.length > 0) {
									this.$refs.couponSelector.show()
								} else {
									this.confirmStopCharging()
								}
							}).catch(err => {
								this.confirmStopCharging()
							})**/
						}
					}
				})
			},
			// 优惠券选择回调
			onCouponSelect(coupon) {
				this.selectedCoupon = coupon
				this.confirmStopCharging()
			},
			// 确认结束充电
			confirmStopCharging() {
				const params = {
					orderId: this.currentOrder.id,
					couponId: this.selectedCoupon?.id ? [this.selectedCoupon?.id] : []
				}
				this.$http_api.finishOrder(params).then(res => {
					uni.$u.toast('结束充电成功')
					this.refresh()
				}).finally(() => {
					this.selectedCoupon = null
					this.currentOrder = null
				})
			},
			refresh() {
				this.isLoading = false;
				this.isFinished = false;
				this.getlist(true);
			},
			// Add payment callback methods
			onPaymentSuccess({ orderId }) {
				this.showPayment = false;
				uni.$u.toast('支付成功');
				const index = this.orderList.findIndex(item => item.orderNumber == orderId);
				if (index >= 0) {
					this.orderList[index].status = 3;
					return;
				}
				this.resetOrderList();
			},
			onPaymentFail() {
				uni.$u.toast('支付失败')
			}
		},
		filters: {
			formatTime(time) {
				return formatNewTimestamp(time);
			},
			formatMinutes(minute) {
				return formatMinutes(minute)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding-bottom: 120rpx;
		font-family: "PINGFANG";
	}

	.tab-header {
		display: flex;
		background: #fff;
		padding: 20rpx 0;
		position: sticky;
		top: var(--window-top);
		z-index: 1;
		overflow-x: auto;
		white-space: nowrap;

		.tab-item {
			flex: none;
			width: calc(100vw / 5);
			text-align: center;
			position: relative;
			
			text {
				font-size: 32rpx;
				color: #333333;
			}

			&.active {
				text {
					color: #42E0A2;
					font-weight: 500;
				}

				.tab-line {
					width: 50rpx;
					height: 6rpx;
					background: #42E0A2;
					position: absolute;
					bottom: -20rpx;
					left: 50%;
					transform: translateX(-50%);
					border-radius: 69rpx;
				}
			}
		}
	}

	.order-list {
		padding: 20rpx;
		width: calc(100% - 40rpx);
	}

	.order-item {
		background: #fff;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
		position: relative;

		.order-header {
			display: flex;
			justify-content: space-between;
			margin-bottom: 24rpx;
			border-bottom: 1rpx solid #eee;
			padding: 17rpx 10rpx;
			width: 95%;
			.order-no {
				font-size: 24rpx;
				color: #666;
			}

			.order-time {
				font-size: 24rpx;
				color: #999;
			}
		}

		.order-content {
			display: flex;
			align-items: flex-start;

			.charging-info {
				flex: 1;
				margin-right: 20rpx;

				.info-item {
					margin-bottom: 8rpx;
					font-size: 24rpx;
					display: flex;

					.title {
						color: #333;
						font-size: 26rpx;
					}

					.label {
						color: #666;
						margin-right: 10rpx;
					}

					.value {
						color: #666;
					}
				}
			}

			.order-amount {
				padding: 10rpx 15rpx;
				text-align: center;
				height: 180rpx; 
				display: flex;
				flex-direction: column;
				justify-content: flex-end;

				.amount {
					display: block;
					font-size: 36rpx;
					color: #FC0A01;
					font-weight: bold;
				}

				.amount-label {
					font-size: 24rpx;
					color: #333;
					margin-top: 10rpx;
				}

				.order-status {
					padding: 2rpx 10rpx;
					color: #fff;
					font-size: 24rpx;
					border-radius: 24rpx;
					line-height: 1.4;
					margin-bottom: auto;
					width: 76rpx;
					margin-left: auto;
					margin-right: auto;
				}
				
				.abnormal {
					color: #FC0A01;
					background: rgba(#FC0A01, 0.2);
					border: 2rpx solid #FC0A01;
				}
			}
		}
	}

	.buttons {
		border-top: 1rpx solid #eee;
		margin-top: 20rpx;
		padding-top: 20rpx;
		justify-content: flex-end;
	}

	.button {
		padding: 15rpx 40rpx;
		border: 1rpx solid #42E0A2;
		color: #42E0A2;
		border-radius: 40rpx;
		font-size: 24rpx;
	}
</style>